package com.mocchira.music.radio;

import java.io.File;

import org.json.JSONArray;
import org.json.JSONObject;

import android.content.Context;
import android.util.Log;
import android.widget.Toast;

public class LatestTracksManager implements IDownloadListener {
    private boolean isExecuting = false;
    private Context ctx;
    private DownloadManager dlManager;
    private File tagIdxFile;
    private JSONArray tagJson = null;
    private static LatestTracksManager manager = null;
    private static final long LATEST_EXPIRE = 3600 * 12 * 1000;
    private static final String LATEST_IDX_FNAME = "idx.json";
    private static final String LATEST_URL_BASE = "http://shopping.mocchira.com/latest/";
    private static final String LATEST_TAG_IDX_URL = LATEST_URL_BASE + LATEST_IDX_FNAME;
    
    public static LatestTracksManager getInstance(Context ctx) {
        if (manager == null) {
            manager = new LatestTracksManager(ctx);
        }
        return manager;
    }
    private LatestTracksManager(Context ctx) {
        this.ctx = ctx;
        dlManager = new DownloadManager(ctx, this);
        tagIdxFile = new File(ctx.getFilesDir(), "latest__tag__.json");
    }
    private boolean isExpire(File file) {
        if (file == null || !file.canRead())
            return true;
        long lastMod = file.lastModified();
        return ((System.currentTimeMillis() - lastMod) > LATEST_EXPIRE);
    }
    //@note string including return values is encoded as urlencode utf-8
    public JSONArray getLatestTags() {
        if (isExpire(tagIdxFile)) {
            if (isExecuting) return null;
            isExecuting = true;
            dlManager.enqueue(LATEST_TAG_IDX_URL);
            return null;
        } else if (tagJson == null) {
            try {
                String hotStr = FileUtil.getContents(tagIdxFile);
                JSONObject root = new JSONObject(hotStr);
                tagJson = root.getJSONArray("tags");
            } catch (Exception ex) {
                Log.e("fmr", ex.getMessage(), ex);
                dlManager.enqueue(LATEST_TAG_IDX_URL);
                return null;
            }
        }
        return tagJson;
    }
    @Override
    public void onComplete(String url, File tmpFile, Exception ex) {
        isExecuting = false;
        if (ex != null) {
            Toast.makeText(ctx, R.string.msg_network_err, Toast.LENGTH_LONG).show();
        } else {
            tmpFile.renameTo(tagIdxFile);
            getLatestTags();
        }
    }

}
